import router from './router'
import store from './store'
import {Message} from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import {getToken} from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({showSpinner: false}) // NProgress Configuration

const whiteList = ['/login', '/companyReg', '/auth-redirect'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  console.log(from.path + ">跳转到>" + to.path)
  document.title = getPageTitle(to.meta.title)
  const hasToken = getToken()

  if (hasToken) {
    console.log("hasToken:" + from.path + ">跳转到>" + to.path)
    console.log("to目的", to)
    if (to.path === '/login') {
      next({path: '/'})
    } else {
      //用户的菜单是通过后台查询放到vuex中的，页面刷新时vuex会清除数据，所以每次跳转页面都要先判断下vuex中是否有菜单，
      //没有菜单的话会请求后台放回菜单再放到vuex中
      const hasFetchPrivileges = store.getters.hasFetchPrivilege
      if (hasFetchPrivileges) {
        console.log("hasFetchPrivileges:" + from.path + ">跳转到>" + to.path)
        next()
      } else {
        try {
          console.log('跳转界面前vuex中没有菜单权限信息，从后台重新请求。每次F5刷新界面都会执行')
          await store.dispatch('user/getUserInfo')
          // 从后台获取用户分配的菜单权限
          const myMenuPrivileges = await store.dispatch('user/getMyMenuPrivilege')
          // 把后台获取到的菜单权限转换为router后放到vuex
          const accessRoutes = await store.dispatch('permission/generateMyRoutes', myMenuPrivileges)
          console.log("获取到权限路由有:", accessRoutes)
          router.addRoutes(accessRoutes)
          next({...to, replace: true})
        } catch (error) {
          Message.error(error || '跳转界面请求用户相关信息错误,不应该会出现这个问题')
          console.log('跳转界面前请求用户相关信息错误,不应该会出现这个问题', error)
          await store.dispatch('user/logout')
          next(`/login?redirect=${to.path}`)
        }
      }
    }
  } else {
    console.log("noToken:" + from.path + ">跳转到>" + to.path)
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
